import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'controller.dart';

class ServerDockerPage extends GetView<ServerDockerController> {
  const ServerDockerPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(  
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
        title: Obx(() => Text('${controller.server.value?.name ?? ""} - Docker')),
        actions: [
          // 分组显示开关（仅在有 Compose 容器时显示）
          Obx(() {
            if (controller.composeProjects.isEmpty) return const SizedBox.shrink();
            return IconButton(
              icon: Icon(
                controller.groupByCompose.value ? Icons.folder : Icons.folder_outlined,
                color: controller.groupByCompose.value ? Colors.blue : null,
              ),
              onPressed: () => controller.groupByCompose.value = !controller.groupByCompose.value,
              tooltip: controller.groupByCompose.value ? '取消分组' : '按项目分组',
            );
          }),
          // 自动刷新开关
          Obx(() => IconButton(
            icon: Icon(
              controller.autoRefresh.value ? Icons.refresh : Icons.refresh_outlined,
              color: controller.autoRefresh.value ? Colors.green : null,
            ),
            onPressed: () => controller.toggleAutoRefresh(!controller.autoRefresh.value),
            tooltip: controller.autoRefresh.value ? '关闭自动刷新' : '开启自动刷新',
          )),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }

        if (controller.errorMessage.value.isNotEmpty) {
          return _buildErrorView();
        }

        if (controller.containers.isEmpty) {
          return _buildEmptyView();
        }

        return RefreshIndicator(
          onRefresh: () => controller.loadContainers(showLoading: false),
          child: controller.groupByCompose.value 
            ? _buildGroupedView()
            : _buildListView(),
        );
      }),
    );
  }

  /// 构建列表视图
  Widget _buildListView() {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: controller.containers.length,
      itemBuilder: (context, index) {
        return _buildContainerCard(controller.containers[index]);
      },
    );
  }

  /// 构建分组视图
  Widget _buildGroupedView() {
    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        // Compose 项目分组
        ...controller.composeProjects.map((project) {
          final containers = controller.getContainersByProject(project);
          return _buildComposeProjectSection(project, containers);
        }),
        // 独立容器
        if (controller.standaloneContainers.isNotEmpty) ...[
          if (controller.composeProjects.isNotEmpty) const SizedBox(height: 16),
          _buildStandaloneSection(controller.standaloneContainers),
        ],
      ],
    );
  }

  /// 构建 Compose 项目区域
  Widget _buildComposeProjectSection(String projectName, List<DockerContainer> containers) {
    final allRunning = containers.every((c) => c.isRunning);
    final anyRunning = containers.any((c) => c.isRunning);
    
    return Obx(() {
      final isExpanded = controller.isProjectExpanded(projectName);
      
      return Card(
        margin: const EdgeInsets.only(bottom: 12),
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: Column(
          children: [
            // 项目头部（可点击展开/折叠）
            InkWell(
              onTap: () => controller.toggleProjectExpanded(projectName),
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(12),
                topRight: Radius.circular(12),
              ),
              child: Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.blue[50],
                  borderRadius: BorderRadius.only(
                    topLeft: const Radius.circular(12),
                    topRight: const Radius.circular(12),
                    bottomLeft: isExpanded ? Radius.zero : const Radius.circular(12),
                    bottomRight: isExpanded ? Radius.zero : const Radius.circular(12),
                  ),
                ),
                child: Row(
                  children: [
                    // 展开/折叠图标
                    Icon(
                      isExpanded ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_right,
                      color: Colors.blue[700],
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    // 项目图标
                    Icon(Icons.folder, color: Colors.blue[700], size: 20),
                    const SizedBox(width: 8),
                    // 项目名称和容器数
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            projectName,
                            style: TextStyle(
                              fontSize: 15,
                              fontWeight: FontWeight.bold,
                              color: Colors.blue[900],
                            ),
                          ),
                          Text(
                            '${containers.length} 个容器',
                            style: TextStyle(
                              fontSize: 11,
                              color: Colors.blue[600],
                            ),
                          ),
                        ],
                      ),
                    ),
                    // 状态徽章
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                      decoration: BoxDecoration(
                        color: allRunning ? Colors.green[100] : anyRunning ? Colors.orange[100] : Colors.grey[300],
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Text(
                        allRunning ? '运行中' : anyRunning ? '部分运行' : '已停止',
                        style: TextStyle(
                          fontSize: 10,
                          color: allRunning ? Colors.green[800] : anyRunning ? Colors.orange[800] : Colors.grey[700],
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            
            // 展开内容
            if (isExpanded) ...[
              // 项目操作按钮
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                color: Colors.blue[25],
                child: Row(
                  children: [
                    if (!allRunning)
                      Expanded(
                        child: ElevatedButton.icon(
                          onPressed: () => controller.startComposeProject(projectName),
                          icon: const Icon(Icons.play_arrow, size: 14),
                          label: const Text('启动', style: TextStyle(fontSize: 11)),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.green,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(vertical: 6),
                            minimumSize: const Size(0, 32),
                          ),
                        ),
                      ),
                    if (anyRunning) ...[
                      if (!allRunning) const SizedBox(width: 6),
                      Expanded(
                        child: ElevatedButton.icon(
                          onPressed: () => controller.stopComposeProject(projectName),
                          icon: const Icon(Icons.stop, size: 14),
                          label: const Text('停止', style: TextStyle(fontSize: 11)),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.orange,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(vertical: 6),
                            minimumSize: const Size(0, 32),
                          ),
                        ),
                      ),
                    ],
                    const SizedBox(width: 6),
                    Expanded(
                      child: OutlinedButton.icon(
                        onPressed: () => controller.restartComposeProject(projectName),
                        icon: const Icon(Icons.refresh, size: 14),
                        label: const Text('重启', style: TextStyle(fontSize: 11)),
                        style: OutlinedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(vertical: 6),
                          minimumSize: const Size(0, 32),
                        ),
                      ),
                    ),
                    const SizedBox(width: 6),
                    SizedBox(
                      width: 36,
                      height: 32,
                      child: IconButton(
                        onPressed: () => controller.deleteComposeProject(projectName),
                        icon: const Icon(Icons.delete_outline, size: 18),
                        color: Colors.red,
                        tooltip: '删除项目',
                        padding: EdgeInsets.zero,
                      ),
                    ),
                  ],
                ),
              ),
              // 容器列表
              ...containers.map((container) => Padding(
                padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
                child: _buildContainerCard(container, isInProject: true),
              )),
            ],
          ],
        ),
      );
    });
  }

  /// 构建独立容器区域
  Widget _buildStandaloneSection(List<DockerContainer> containers) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 4, bottom: 8),
          child: Row(
            children: [
              Icon(Icons.widgets_outlined, size: 16, color: Colors.grey[600]),
              const SizedBox(width: 6),
              Text(
                '独立容器 (${containers.length})',
                style: TextStyle(
                  fontSize: 13,
                  fontWeight: FontWeight.bold,
                  color: Colors.grey[700],
                ),
              ),
            ],
          ),
        ),
        ...containers.map((container) => _buildContainerCard(container)),
      ],
    );
  }

  /// 构建容器卡片
  Widget _buildContainerCard(DockerContainer container, {bool isInProject = false}) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      child: Padding(
        padding: const EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题行
            Row(
              children: [
                // 状态指示器
                Container(
                  width: 8,
                  height: 8,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: container.isRunning ? Colors.green : Colors.grey,
                  ),
                ),
                const SizedBox(width: 8),
                // 容器名称
                Expanded(
                  child: Text(
                    container.name.replaceFirst('/', ''),
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                const SizedBox(width: 8),
                // 状态徽章
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                  decoration: BoxDecoration(
                    color: container.isRunning ? Colors.green[50] : Colors.grey[200],
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Text(
                    container.isRunning ? '运行' : '停止',
                    style: TextStyle(
                      fontSize: 10,
                      color: container.isRunning ? Colors.green[700] : Colors.grey[600],
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            
            // 容器信息
            _buildInfoRow(Icons.image, '镜像', container.image),
            const SizedBox(height: 4),
            _buildInfoRow(Icons.fingerprint, 'ID', container.id.substring(0, 12)),
            const SizedBox(height: 4),
            _buildInfoRow(Icons.access_time, '状态', container.status),
            if (container.ports.isNotEmpty) ...[
              const SizedBox(height: 4),
              _buildInfoRow(Icons.cloud, '端口', container.ports),
            ],
            // Compose 信息（仅在非分组视图且是 Compose 容器时显示）
            if (!isInProject && container.isComposeContainer) ...[
              const SizedBox(height: 4),
              _buildInfoRow(Icons.folder, '项目', container.composeProject ?? '-'),
              if (container.composeService != null) ...[
                const SizedBox(height: 4),
                _buildInfoRow(Icons.widgets, '服务', container.composeService!),
              ],
            ],
            
            const Divider(height: 16, thickness: 0.5),
            
            // 操作按钮
            Row(
              children: [
                if (container.canStart)
                  Expanded(
                    child: ElevatedButton.icon(
                      onPressed: () => controller.startContainer(container),
                      icon: const Icon(Icons.play_arrow, size: 14),
                      label: const Text('启动', style: TextStyle(fontSize: 11)),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green,
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(vertical: 6),
                        minimumSize: const Size(0, 32),
                      ),
                    ),
                  ),
                if (container.canStop)
                  Expanded(
                    child: ElevatedButton.icon(
                      onPressed: () => controller.stopContainer(container),
                      icon: const Icon(Icons.stop, size: 14),
                      label: const Text('停止', style: TextStyle(fontSize: 11)),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.orange,
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(vertical: 6),
                        minimumSize: const Size(0, 32),
                      ),
                    ),
                  ),
                const SizedBox(width: 6),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () => controller.restartContainer(container),
                    icon: const Icon(Icons.refresh, size: 14),
                    label: const Text('重启', style: TextStyle(fontSize: 11)),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 6),
                      minimumSize: const Size(0, 32),
                    ),
                  ),
                ),
                const SizedBox(width: 6),
                SizedBox(
                  width: 36,
                  height: 32,
                  child: IconButton(
                    onPressed: () => controller.deleteContainer(container),
                    icon: const Icon(Icons.delete_outline, size: 18),
                    color: Colors.red,
                    tooltip: '删除',
                    padding: EdgeInsets.zero,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建信息行
  Widget _buildInfoRow(IconData icon, String label, String value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Icon(icon, size: 14, color: Colors.grey[600]),
        const SizedBox(width: 6),
        Text(
          '$label: ',
          style: TextStyle(
            fontSize: 11,
            color: Colors.grey[600],
            fontWeight: FontWeight.w500,
          ),
        ),
        Expanded(
          child: Text(
            value,
            style: const TextStyle(fontSize: 11),
            overflow: TextOverflow.ellipsis,
            maxLines: 2,
          ),
        ),
      ],
    );
  }

  /// 构建空视图
  Widget _buildEmptyView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.widgets_outlined, size: 80, color: Colors.grey[300]),
          const SizedBox(height: 20),
          Text(
            '没有找到 Docker 容器',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 10),
          Text(
            '服务器上可能没有运行任何容器',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[400],
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton.icon(
            onPressed: () => controller.loadContainers(),
            icon: const Icon(Icons.refresh),
            label: const Text('重新加载'),
          ),
        ],
      ),
    );
  }

  /// 构建错误视图
  Widget _buildErrorView() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 64, color: Colors.red[300]),
            const SizedBox(height: 16),
            Text(
              controller.errorMessage.value,
              style: TextStyle(fontSize: 16, color: Colors.grey[600]),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 24),
            ElevatedButton.icon(
              onPressed: () => controller.loadContainers(),
              icon: const Icon(Icons.refresh),
              label: const Text('重试'),
            ),
          ],
        ),
      ),
    );
  }
}

